var watch = require('watch');
const { exec } = require('child_process');
const { sleep } = require('@midwayjs/bootstrap/dist/util');
const { RESTART_OCTOPODA } = require('./cmd');
let program = null;
let watchProcess = null;
watchOctopoda();
process.on('SIGINT', () => {
  watched = false;
  program.kill('SIGKILL');
  watchProcess.kill('SIGKILL');
  process.exit(0);
});
function startProcess() {
  // 执行js脚本
  program = exec('npm run dev', function (error, stdout, stderr) {
    if (error) {
      console.error(`exec error: ${error}`);
      return;
    }
    console.log(`stdout: ${stdout}`);
    console.error(`stderr: ${stderr}`);
  });

  // 打印输出到控制台
  program.stdout.on('data', data => {
    console.log(data.toString());
  });
}

// 有了start，还要有个restart
function restartProcess() {
  if (program !== null) {
    try {
      // 清除进程，
      program.kill('SIGKILL');
    } catch (error) {
      console.log('Exception: ' + error.message, 'bad');
    }
  }

  // 然后这里再次启动，可以说很像清除定时器的操作了～
  startProcess();
}
startProcess();
var watched = false;
function watchOctopoda(){
  watchProcess = exec('node ./dev/watchProcess.js', function(error, stdout, stderr){
    console.log(error, stdout, stderr);
  });
  watchProcess.stdout.on('data', function(message) {
    restartProcess();
    console.log('message :' + message);
  });
}
